package com.heima.behavior.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.UnLikeBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: heima-leadnews
 * @description:
 * @author: lydms
 * @create: 2024-04-12 17:08
 **/

@Service
@Slf4j
@Transactional
public class UnLikeBehaviorServiceImpl implements UnLikeBehaviorService {


    @Autowired
    private CacheService cacheService;
    /**
     * 不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //  检查参数
        if (dto == null || dto.getArticleId() == null || dto.getType() > 1 ||dto.getType() < 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //  判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 存入redis
        if(dto.getType() == 0){
            log.info("不喜欢文章{}，{},{}",dto.getArticleId(),user.getId(),dto);
           cacheService.hPut(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString(), JSON.toJSONString(dto));

        }else {
            log.info("取消不喜欢文章{}，{},{}",dto.getArticleId(),user.getId(),dto);
            cacheService.hDelete(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString() );
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
